/*
* dataview 私有方法  网格列表
* */
const dvFunPrivateEdit = {
//允许行编辑的数据
  rowEditRender(column) {
    let editRender = column.editRender ? column.editRender : '$input' //渲染模板
    let options = column.dict ? this.utils.getDictDataList(column.dict) : this.viewFormDictionaries[column.name] //数据源
    column.dict && column.dict == 'common_yes_no' && options.forEach(item => {
      item.value = this.utils.convertToBoolean(item.value)
    })
    let optionProps = {label: 'label', value: 'value'}
    if (options && !column.dict) {
      //非字典，从数据库查询

      optionProps = {label: 'name', value: 'id'}
    }
    let event = {change: this.rowEditSelectChange}
    if (['$input', 'ElInput'].includes(editRender)) {
      event = {input: this.rowEditInputChange}
    }
    return {
      name: editRender,
      options,
      optionProps,
      autoselect: true,
      events: event,
      props: {
        disabled: !this.isColumnEdit(column),
        dataview: this,
        tableData: this.viewFormEditDatas,
        tableQueries: this.editQueries,
        userParam: this.editUserParam,
        tableColumns: this.viewFormEditColumns,
        clearable: true,
        type: editRender.toLowerCase().indexOf('date') > -1 ? 'date' : null,
        format: editRender.toLowerCase().indexOf('date') > -1 ? 'yyyy-MM-dd' : null,
      }
    }
  },
  //编辑关闭事件
  async editClosedEvent({row, column}) {
    let rowIndex = this.getGrid().getRowIndex(row)
    let that = this
    let flagNullRow = true //是否为空行
    Object.keys(row).forEach((key) => {
      if (key != this.rowPK && row[key] && key != '_isEditPlaceholder') {
        flagNullRow = false
      }
    })

    //编辑占位行，不使用关闭功能
    if (this.isEditPlaceholderRow(row)) {
      if (!this.validateRow(row)) { //验证失败
        console.log('valid 1')
        return
      }
    }

    if (flagNullRow) {
      this.rows.splice(0, 1)
      this.$refs.tbMain.loadData(this.rows)
      console.log('valid 2')
      return
    }
    const errMap = await this.getGrid().fullValidate(row).catch(errMap => errMap)
    //校验不通过
    if (errMap != undefined) {
      console.log('valid 3 errMap', errMap,column)
      if (column.editRender && column.editRender.name) {
        let validOne
        let errMsgArr = [`第${rowIndex + 1}行保存校验失败`]
        Object.keys(errMap).forEach(key => {
          validOne = errMap[key]
          if (validOne.findIndex(item => item.rule && item.rule.required) != -1) {
            errMsgArr.push(`${validOne[0].column.title}为必填项`)
          } else{
            errMsgArr.push(`${validOne[0].column.title}校验失败`)
          }
        })
        this.utilMessage.warning(errMsgArr.join('<br/>'))
      }

      return
    }


    //输入值与数据库值不一样
    //this.currentRow[column.property] != column.model.value  保存之后，字段进行了修改
    //this.currentRow[column.property] != row[column.property]  保存之前，字段进行了修改
    if (this.isRowEditChange(row) || this.isEditPlaceholderRow(row)) {
      let xTable = this.$refs.tbMain
      let field = column.property
      let cellValue = row[field]
      if (
        column.model.value === undefined && row[this.primaryKey] && !this.isEditPlaceholderRow(row)
      ) { //解决一个新增行添加报错的问题
        console.log('valid 4')
        return
      }
      //追加拦截器需要使用的参数
      row = this.utils.appendParamForInterceptor(this, 'dataviewsave', row)
      row._isSaveing = true
      this.$ajax.post(this.saveEntry, row).then((response) => {
        let isNew = this.strings.isBlank(row[this.primaryKey])
        if (response.success) {
          row[this.primaryKey] = response.data[this.primaryKey]
          if (row.showExpand) {
            row.childData = response.data.childData
          }
          row._isEditPlaceholder = false
          this.utilMessage.success(`第${rowIndex + 1}行保存成功`)
        } else {
          //  保存失败,恢复源值
          if (column.model.value !== undefined) {
            row[column.property] = column.model.value
            const oldRow = JSON.parse(JSON.stringify(row))
            this.$set(row, this.primaryKey, oldRow[this.primaryKey])
          }
        }
        if (!row[that.primaryKey] && response.success) {
          //新增数据刷新
          let newRecord = that.rows.find(item => item[this.rowPK] == row[this.rowPK])
          this.$set(newRecord, this.primaryKey, response.data[this.primaryKey])
          this.$set(newRecord, '_isEditPlaceholder', false)
        }

        // 赋值属性
        let fieldSetList = []
        Object.keys(response.data).forEach(key => {
          // 创建人、创建时间只有新增的时候才更新，因为更新操作没有返回这俩字段信息
          if (!isNew && ['creator', 'gmtCreate'].includes(key)) {
          } else {
            this.$set(row, key, response.data[key])
            fieldSetList.push(key)
          }
        })
        that.propParentPage && that.propParentPage.$emit('refresh-row')
        this.$emit('after-save', row)
        if (response.success) {
          this.$set(row, '_isEditPlaceholder', false)
          if (true != that.propDisabledRowSaveClearActived) {
            this.getGrid().clearActived()
          }

          // 局部更新
          if (fieldSetList.length > 0) {
            fieldSetList.forEach(fieldSet => {
              this.getGrid().reloadRow(row, null, fieldSet)
            })
          }

          this.insertFirst(true)
        }
        row._isSaveing = false
        this.$emit('afterTableDataChange')
      })
    }
  },

  //是否有添加按钮
  isHaveAdd() {
    let btns = this.cpToolbar != null ? this.cpToolbar.buttons : null
    return btns && btns.length > 1 && btns.findIndex(btn => btn.code == 'vb-add') != -1
  },

  //追加第一行
  async insertFirst(isAddNew) {
    if (this.propNoEditRow && this.propNoEditRow == true) {
      return
    }
    //非行编辑忽略  (isAddNew && isAddNew == true)
    if (
      (!this.editable || !this.isHaveAdd())
      && (
        !(isAddNew && isAddNew == true)
      )
    ) {
      return
    }

    //已经添加过了
    if (this.haveEditPlaceholderRow()) {
      return
    }

    const record = {
      _isEditPlaceholder: true,
    }
    let { row: newRow } = await this.getGrid().insertAt(record, null)
    this.rowEditFirst = newRow

    if (
      (
        (this.propParentData && this.propParentData.id)
        ||  (this.propCurrentRow && this.propCurrentRow.id)
      )

      ||  (!this.propActiveFirstAuto)
    ) {
      return
    }
    this.getGrid().setActiveRow(newRow)
    let editColumnsFirst = this.cpColumns.filter(column => this.isColumnEdit(column))[0]
    let param = await this.getGrid().setActiveCell(newRow, editColumnsFirst.name)
  },

  //激活第一行编辑
  async activeFirst(isAddNew) {
    //非行编辑忽略
    if (this.editable || this.isHaveAdd()
    || (isAddNew && isAddNew == true)
    ) {
      if (!this.rowEditFirst) {  //编辑行不存在
        //此处加超时，防止调用顺序产生的重复添加编辑行的问题
        setTimeout(() => {
          if (!this.rowEditFirst) {
            this.insertFirst(isAddNew)
          } else {
            let editColumnsFirst = this.cpColumns.filter(column => this.isColumnEdit(column))[0]
            this.getGrid().setActiveCell(this.rowEditFirst, editColumnsFirst.name)
          }
        }, 500)
      } else {
        let editColumnsFirst = this.cpColumns.filter(column => this.isColumnEdit(column))[0]
        if (editColumnsFirst) {
          let param = await this.getGrid().setActiveCell(this.rowEditFirst, editColumnsFirst.name)
        }
      }
    }
  },
  /**
  * @Description：激活当前行下一个单元格或者指定行编辑
  * @Author wyt
  * @Date 2022/1/14
  * @param columnNameTo 激活指定的单元格
  */
  async activeNext(columnNameTo) {
    //非行编辑忽略
    if (!this.editable) {
      return
    }

    let that = this
    setTimeout(() => {
      let editColumns = that.cpColumns.filter(column => this.isColumnEdit(column))
      let indexCurr = editColumns.findIndex(ob => ob.name == this.editColumnName)
      let editColumnsRight = editColumns[indexCurr + 1]
      if (columnNameTo) {
        indexCurr = editColumns.findIndex(ob => ob.name == columnNameTo)
        editColumnsRight = editColumns[indexCurr]
      }

      //右边没有编辑列时 激活下一行的左侧第一个文本编辑单元格，如果有的话
      if (!editColumnsRight) {
        let rowNextDom = $(this.editCell).closest('.vxe-body--row').next()
        if (rowNextDom) {
          let rowIndex = this.getGrid().getRowIndex(this.editRow)
          let rowNext = this.getGrid().getData(rowIndex + 1)

          //先找文本类型的
          editColumnsRight = editColumns.filter(column => !['FortenDataviewDown', 'FortenVxeDate'].includes(column.editRender))[0]
          console.log('editColumnsRightfind1', editColumnsRight)
          if (!editColumnsRight) {  //未找到则找复杂控件的
            editColumnsRight = editColumns.filter(column => ['FortenDataviewDown', 'FortenVxeDate'].includes(column.editRender))[0]
          }

          //编辑过需要保存，做个延迟
          let isEdit = this.isRowEditChange(this.currentRow)

          this.getGrid().clearActived()

          this.editColumnName = editColumnsRight.name
          this.editRow = rowNext
          this.editCell = rowNextDom.find('.' + this.editColumnName)[0]

          if (isEdit) {
            setTimeout(() => {
              this.getGrid().setCurrentRow(this.editRow)
              this.activeNext(editColumnsRight.name)
            }, 500)
          } else {
            this.getGrid().setCurrentRow(this.editRow)
            this.activeNext(editColumnsRight.name)
          }
        }
      } else {
        this.editColumnName = editColumnsRight.name
        this._doActiveNext(editColumnsRight)
      }
    }, 100)
  },

  async _doActiveNext(editColumnsRight) {
    //复杂单元格使用单元格点击事件
    if (editColumnsRight.editRender && ['FortenDataviewDown', 'FortenVxeDate'].includes(editColumnsRight.editRender)) {
      let cellFind = $(this.editCell).siblings().filter('.' + editColumnsRight.name)
      if (cellFind && cellFind.length > 0) {
        this.editCell = cellFind[0]
        this.editColumnName = this.editColumnName
        await this.scrollToEditCell()
        //手动聚焦
        this.focusCellForEdit(editColumnsRight.editRender)
      }
    } else {
      await this.getGrid().setActiveCell(this.editRow, this.editColumnName)
      await this.scrollToEditCell()
      if (!$(this.editCell).find('.vxe-input--inner').is('focus')) {
        // $(this.editCell).find('.vxe-input--inner').focus()
      }
    }
  },

  //滚动到当前激活的单元格中  【不可用，有问题】
  scrollToActiveColumn() {
    let left = $(this.editCell).offset().left
    let top = $(this.editCell).offset().top
    this.getGrid().scrollTo(left, top)
  },

  //是否是编辑占位行
  isEditPlaceholderRow(row) {
    if (row && row._isEditPlaceholder != undefined && row._isEditPlaceholder == true) {
      return true
    }
    return false
  },

  //是否是编辑占位行
  haveEditPlaceholderRow() {
    if (
      this.getGrid().getTableData()
      &&      this.getGrid().getTableData().fullData
      &&      this.getGrid().getTableData().fullData.filter(row => row._isEditPlaceholder && row._isEditPlaceholder == true).length > 0) {
      return true
    }

    return false
  },

  // 手动清除校验
  clearValidate() {
    this.getGrid().clearValidate()
  },

  rowEditInputChange({row, column}) {
    let value = row[column.property]
    //数量字段
    if (!this.utilFieldMap.rowEditInputIgnore(this.propViewKey, column.property) && column.property.toLowerCase().indexOf('qty') != -1) {
      //包装数据，必须整数
      if (column.property == 'packageQty' && (!this.utilNum.isInt(value) || value <= 0)) {
        this.utilMessage.warning('包装数量请输入大于0的整数')
        row[column.property] = column.model.value
      }
      //其他的不小于0的数字
      if (!this.utilNum.isNumZS(value)) {
        this.utilMessage.warning('该字段必须为正数')
        row[column.property] = column.model.value
      }
    }
    if (this.rowEditInputValid) {
      if (!this.rowEditInputValid(row, column,column.property, value)) {
        row[column.property] = column.model.value
        return
      }
    }
    this.editColumnName = column.property
    this.$emit('edit-input', {row, column})
  },
  rowEditSelectChange({row, column}) {
    //追加拦截器需要使用的参数
    row = this.utils.appendParamForInterceptor(this, 'dataviewsave', row)
    this.$emit('select-change', {row, column})

    //不自动激活
    if (this.cpDisabledActiveNext) {
      return
    }
    if (this.strings.isNotBlank(row[column.property])) {
      this.activeNext()
    }
  },

  //校验行
  validateRow(row) {
    if (!this.rules) {
      return true
    }
    let comumnEditsRequired = this.cpColumns.filter(
      column => (this.isColumnEdit(column))
        && this.rules[column.name] && this.rules[column.name].filter(ob => ob.required).length > 0
        && this.strings.isBlank(row[column.name])
    )

    if (comumnEditsRequired && comumnEditsRequired.length > 0) {
      let errMsgArr = ['保存校验失败']
      comumnEditsRequired.forEach(row => {
        errMsgArr.push(`${row.title}为必填项`)
      })
      this.utilMessage.warning(errMsgArr.join('<br/>'))
      return false
    }
    return true
  },

  //判断行是否编辑过，只要有一个编辑过
  isRowEditChange(rowEditNow) {
    let isChange = false

    if (!rowEditNow) {
      return false
    }
    //获取原始数据
    if (!this.editRowOld) {
      this.utilMessage.warning('获取编辑行数据失败')
      return false
    }

    let columnNameEdit = this.cpColumns.filter(column => this.isColumnEdit(column)).map((column) => {
      return column.name
    })
    if (!columnNameEdit || columnNameEdit.length < 1) {
      return false
    }
    let changeFieldArr = Object.keys(this.editRowOld).filter(fieldName => columnNameEdit.includes(fieldName) && rowEditNow[fieldName] != this.editRowOld[fieldName])
    if (!changeFieldArr ||  changeFieldArr.length < 1) {
      return false
    }

    return true
  },

  //单元格是否只读
  isCellReadonly(column, scope) {
    if (!scope) {
      return false
    }
    if (!this.isColumnEdit(column)) {  //没有编辑渲染器的
      return true
    }

    if (this.strings.isNotBlank(scope[this.primaryKey]) && column.name == 'matrName') {  //有主键并且是耗材选择的
      return true
    }
    return false
  },
  //行编辑激活，每个行编辑激活只会触发一次
  editActived(param) {
    this.editRow = param.row
    this.editRowOld = JSON.parse(JSON.stringify(param.row))
    this.editCell = param.cell
    this.editColumnName = param.column.property
    if (!param.column || !param.column.editRender || !param.column.editRender.name) {
      return null
    }

    this.focusCellForEdit(param.column.editRender.name)
  },

  focusCellForEdit(editRender) {
    if (editRender == 'FortenVxeDate') { //日期框手动聚焦
      this.$nextTick(() => {
        if (!$(this.editCell).find('.el-input__inner').is('focus')) {
          $(this.editCell).find('.el-input__inner').focus()
        }
      })
    }
    if (editRender == 'customSelect') { //自定义选择
      this.$nextTick(() => {
        if (!$(this.editCell).find('.t-input__inner').is('focus')) {
          $(this.editCell).find('.t-input__inner').focus()
        }
      })
    }
    if (editRender == 'customSelectAlways') { //自定义选择
      this.$nextTick(() => {
        if (!$(this.editCell).find('.t-input__inner').is('focus')) {
          $(this.editCell).find('.t-input__inner').focus()
        }
      })
    }
    if (editRender == 'inputNumberGt0') { //自定义选择
      this.$nextTick(() => {
        if (!$(this.editCell).find('.t-input__inner').is('focus')) {
          $(this.editCell).find('.t-input__inner').focus()
        }
      })
    }
    if (editRender == 'customDatePicker') { //日期-年月日
      this.$nextTick(() => {
        if (!$(this.editCell).find('.t-input__inner').is('focus')) {
          $(this.editCell).find('.t-input__inner').focus()
        }
      })
    }
  },

  //列是否可以编辑
  isColumnEdit(column) {
    //editRender
    if ((column.edit == '1' || column.edit == true) &&  (this.strings.isNotBlank(column.editRender))) {
      return true
    }
    return false
  },

  //滚动到编辑单元格
  async scrollToEditCell() {
    let prevAll = $(this.editCell).prevAll('.vxe-body--column').not('.col--seq').not('.col--checkbox')
    let scrollLeft = 0
    if (!scrollLeft || isNaN(scrollLeft)) {
      scrollLeft = 0
    }

    if (prevAll && prevAll.length > 0) {
      let widthTmp = 0
      let td
      for (let index in prevAll) {
        widthTmp = parseInt(prevAll[index].clientWidth, 0)
        if (!widthTmp || isNaN(widthTmp)) {
          continue
        }
        scrollLeft += widthTmp
      }
    }
    scrollLeft -= 80
    await this.getGrid().scrollTo(scrollLeft, this.getGrid().getScroll().scrollTop)
  }
}

export default dvFunPrivateEdit
